#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

typedef struct msgbuf
{
    long msgtype;
    char msgtext[32];
} MSG;

int main(int argc, const char *argv[]) 
{
    key_t key;
    key = ftok("/", 'b');
    int msqid;

    MSG mymsg;

    msqid = msgget(key, IPC_CREAT | IPC_EXCL | 0664);
    if(msqid == -1) {
        if(errno == EEXIST) {
            printf("消息队列已存在\n");
            msqid = msgget(key, 0664);
        } else {
            perror("msgget");
            return -1;
        }
    } else {
        printf("消息队列创建成功\n");
    }

#if 0
    mymsg.msgtype = 100;
    strcpy(mymsg.msgtext, "hello world");
    msgsnd(msqid, &mymsg, strlen(mymsg.msgtext)+1, 0);
#endif

#if 0
    char buff[128];
    ssize_t n;
    n = msgrcv(msqid, buff, sizeof(buff), 0, 0);
    printf("n = %d, buff:%s\n", n, buff);
#endif

#if 1
    MSG msgbuff;
    ssize_t n;
    n = msgrcv(msqid, &msgbuff, sizeof(MSG)-sizeof(long), 100, 0);
    printf("n = %d, buff:%s\n", n, msgbuff.msgtext);
#endif
    return 0;
}

